//
//  AddPlanViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/11/14.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "AddPlanViewController.h"
#import "AddPlanTableViewCell.h"
#import "AddPlanModel.h"
#import "DutyDropListModel.h"
#define getDropList @"getDropList"//获取可选项列表

@interface AddPlanViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
{
    UITapGestureRecognizer *_tapGesture;//手势
    NSMutableArray *_newModelArr;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) DutyDropListModel *meansListModel;
@property (nonatomic,strong) UILabel *startTitle;//出发title
@property (nonatomic,strong) UILabel *endTitle;//目的title
@property (nonatomic,strong) UILabel *meansTitle;//出行方式title
@property (nonatomic,strong) UILabel *spendTitle;//费用title
@end

@implementation AddPlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationTitle:@"行程计划"];
    [self setLeftBackNavigation];
//    [self creatView];
    [self getDropListRequestWithdataSwith:@"3"];
    // Do any additional setup after loading the view.
}

- (void)creatView{
    _newModelArr=[NSMutableArray arrayWithArray:_dataArr];
    if (_newModelArr.count==0) {
        AddPlanModel *model=[AddPlanModel new];
        [_newModelArr addObject:model];
    }
    //创建列表
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-64) style:UITableViewStylePlain];
    //_myTableView.backgroundColor=[UIColor redColor];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.tag=110;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.showsHorizontalScrollIndicator=NO;
    _tableView.bounces=NO;
    //[self addTableViewUpdateRefresh:_tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [self.view addSubview:_tableView];
    [self addTableViewFootView];
}

- (void)addTableViewFootView{
    //添加提交button
    UIView *footView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 140)];
    footView.backgroundColor=[UIColor clearColor];
    
    UIButton *addButton=[MyControl creatButtonWithFrame:CGRectMake(IPHONE_WIDTH-110, 20, 100, 40) target:self sel:@selector(addButtonClick) tag:130 image:nil title:@"新增路线"];
    addButton.backgroundColor=[UIColor orangeColor];
    addButton.layer.masksToBounds=YES;
    addButton.layer.cornerRadius=5;
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [footView addSubview:addButton];
    
    NSArray *title=@[@"确定"];
    CGFloat buttonWidth=(IPHONE_WIDTH-(title.count+1)*10)/title.count;
    for (int i=0; i<title.count; i++) {
        UIButton *submitButton=[MyControl creatButtonWithFrame:CGRectMake(10*(i+1)+buttonWidth*i,20+addButton.y+addButton.height, buttonWidth, 40) target:self sel:@selector(submitClick:) tag:120+i image:nil title:title[i]];
        submitButton.layer.masksToBounds=YES;
        submitButton.layer.cornerRadius=5;
        [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        if (i==0) {
            submitButton.backgroundColor=COLOR_MIDBLUE;
        }else{
            submitButton.backgroundColor=[UIColor orangeColor];
        }
        [footView addSubview:submitButton];
    }
    _tableView.tableFooterView=footView;
}

- (void)submitClick:(UIButton *)button{
    [self.view endEditing:YES];
    AddPlanModel *model=[_newModelArr lastObject];
    if ([model canAddNewPlan]) {
        if ([model.startStr isEqualToString:model.endStr]) {
            [self setLabelBorderColorWithLabel:_endTitle color:[UIColor redColor]];
            [LZXHelper postMessageWithText:@"对不起，出发地不能与目的地相同!" View:self.view];
            return;
        }
        if (_myBlock) {
            _myBlock(_newModelArr);
        }
        [self backClick];
    }else{
        if (model.startStr.length==0) {
            [self setLabelBorderColorWithLabel:_startTitle color:[UIColor redColor]];
        }else if (model.endStr.length==0){
            [self setLabelBorderColorWithLabel:_endTitle color:[UIColor redColor]];
        }else if (model.meansStr.length==0){
            [self setLabelBorderColorWithLabel:_meansTitle color:[UIColor redColor]];
        }else{
            [self setLabelBorderColorWithLabel:_spendTitle color:[UIColor redColor]];
        }

    }
}

#pragma mark -设置label边框
- (void)setLabelBorderColorWithLabel:(UILabel *)label color:(UIColor *)color{
    label.layer.borderColor=[color CGColor];
    label.layer.borderWidth=1.0;
}

#pragma mark -新增路线

- (void)addButtonClick{
    [self.view endEditing:YES];
    AddPlanModel *model=[_newModelArr lastObject];
    if ([model canAddNewPlan]) {
        AddPlanModel *newModel=[AddPlanModel new];
        [_newModelArr addObject:newModel];
        [_tableView reloadData];
    }else{
        if (model.startStr.length==0) {
            [self setLabelBorderColorWithLabel:_startTitle color:[UIColor redColor]];
        }else if (model.endStr.length==0){
            [self setLabelBorderColorWithLabel:_endTitle color:[UIColor redColor]];
        }else if (model.meansStr.length==0){
            [self setLabelBorderColorWithLabel:_meansTitle color:[UIColor redColor]];
        }else{
            [self setLabelBorderColorWithLabel:_spendTitle color:[UIColor redColor]];
        }
    }
}

#pragma mark -添加手势 取消键盘
- (void)addTapGestureRecognizer{
    //避免手势混乱 所以先移除
    if (_tapGesture) {
        [_tableView removeGestureRecognizer:_tapGesture];
        _tapGesture=nil;
    }
    _tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureClick)];
    [_tableView addGestureRecognizer:_tapGesture];
}
#pragma mark -移除手势
- (void)removeTapGestureRecognizer{
    [_tableView removeGestureRecognizer:_tapGesture];
    _tapGesture=nil;
}
#pragma mark -手势的响应事件
- (void)tapGestureClick{
    [self.view endEditing:YES];
}

#pragma mark - TableViewDelagate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _newModelArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
    //return _personListModel.dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID=@"AddPlanTableViewCell";
    AddPlanTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell=[[AddPlanTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        __weak AddPlanViewController *mySelf=self;
        cell.appearBlock=^(){
            [mySelf addTapGestureRecognizer];
        };
        cell.disAppearBlock=^(){
            [mySelf removeTapGestureRecognizer];
        };
    }
    AddPlanModel *model=_newModelArr[indexPath.section];
    //默认显示从上个页面传过来的地址
    if (indexPath.section==0) {
        if (model.startStr.length==0) {
            model.startStr=self.nowAddress;
        }
        if (model.endStr.length==0&&![self.nextAddress isEqualToString:@"点击进入地图"]) {
            model.endStr=self.nextAddress;
        }
    }else if (indexPath.section==1){
        if (model.startStr.length==0) {
            model.startStr=self.nextAddress;
        }
    }
//    cell.planModel=model;
    [cell setTextViewWithModel:model];
    //将出行方式的model传过去
    cell.dropListModel=_meansListModel;

    if (indexPath.section==_newModelArr.count-1) {
        _startTitle=cell.startTitle;
        _endTitle=cell.endTitle;
        _meansTitle=cell.meansTitle;
        _spendTitle=cell.spendTitle;
    }

//    cell.signButton.selected=model.isSelect;
//    cell.myTitleLabel.text=model.empName;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 50)];
    backView.backgroundColor=[UIColor whiteColor];
    
    UILabel *label=[MyControl creatLabelWithFrame:CGRectMake(10, 5, IPHONE_WIDTH-20, 30) text:[NSString stringWithFormat:@"行程%ld",section+1]];
    label.font=[UIFont boldSystemFontOfSize:17];
    [backView addSubview:label];
    
    return backView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{
    return 40;
}

//开启编辑模式
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section) {
        return YES;
//    }
//    return NO;
}
-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_newModelArr.count>1) {
        // 从数据源中删除
        [_newModelArr removeObjectAtIndex:indexPath.section];
        // 从列表中删除
        [_tableView reloadData];
    }else{
        [_tableView reloadData];
        [LZXHelper postMessageWithText:@"至少需要一项行程计划!" View:self.view];
    }
}


#pragma mark -获取可选项列表
- (void)getDropListRequestWithdataSwith:(NSString *)dataSwith{
    
    NSDictionary *dict=@{
                         @"dataSwith":dataSwith?dataSwith:@"",
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    // __weak AddressBookViewController *mySelf=self;
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getDropList soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        _meansListModel=[[DutyDropListModel alloc]initWithResponse:responseObject];
        if ([_meansListModel.code isEqualToString:@"200"]) {
            [self creatView];
        }else if([_meansListModel.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:_meansListModel.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
